package com.efounder.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.activity.MasterDataActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.chat.widget.BadgeView;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.frame.manager.AppAccountResDownloader;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.frame.xmlparse.EFAppAccountRegistry;
import com.efounder.frame.xmlparse.EFXmlConstants;
import com.efounder.ospmobilelib.R;


import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;

@SuppressLint("SdCardPath")
public class AppAccountLeftDrawerFragment extends BaseFragment implements View.OnClickListener {
    private static final String TAG = "AppLeftDrawerFragment";

    private View rootView;
    private ProgressDialog progressDialog;
    private String url;
    private BadgeView badgeView;
    private UpdateResReceiver updateResReceiver;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_app_account_left_drawer, container, false);
        //头像
        ImageView avatarImageView = (ImageView) rootView.findViewById(R.id.app_account_iv_avatar);
        StubObject mainFrameStub = EFAppAccountRegistry.getStubByID(EFXmlConstants.ID_MAIN_FRAME);
        String mainFrameIcon = mainFrameStub.getString(EFXmlConstants.ATTR_ICON, "");
        avatarImageView.setImageDrawable(Drawable.createFromPath(EFAppAccountUtils
                .getAppAccountImagePath() + "/" + mainFrameIcon));
        //退出
        Button exitButton = (Button) rootView.findViewById(R.id.app_account_exit);
        exitButton.setOnClickListener(this);
        //应用名称
        TextView nameTextView = (TextView) rootView.findViewById(R.id.app_account_tv_name);
        nameTextView.setText(getActivity().getIntent().getStringExtra("nickName"));
        //应用号：
        TextView idTextView = (TextView) rootView.findViewById(R.id.app_account_tv_id);
        idTextView.setText("应用号：" + getActivity().getIntent().getIntExtra("id", 0));
        //应用说明
        TextView descriptionTextView = (TextView) rootView.findViewById(R.id
                .app_account_drawer_description);
        StubObject appStub = EFAppAccountRegistry.getStubByID("main_frame");
        if (appStub != null) {
            descriptionTextView.setText(appStub.getString(EFXmlConstants.ATTR_DESCRIPTION, ""));
        }

        //资源更新_1 加点击监听
        LinearLayout updateResLayout = (LinearLayout) rootView.findViewById(R.id.left_drawer_menu_update_resources_layout);
        updateResLayout.setOnClickListener(this);
        badgeView = createBadgeView(updateResLayout.findViewById(R.id.left_drawer_menu_update_resources_tv));

        //根据xml配置动态生成Menu
        createLeftMenu(inflater);


        return rootView;
    }

    /**
     * 创建标记view
     * @param targetView
     * @return
     */
    public BadgeView createBadgeView(View targetView){
        BadgeView badgeView = new BadgeView(getActivity(), targetView);
        badgeView.setText("1");
        badgeView.setTag("badge");
        badgeView.setBadgeMargin(3, 3);
        badgeView.setBadgeBackgroundColor(getActivity().getResources().getColor(
                com.efounder.chat.R.color.ef_green_dark));
        badgeView.setTextSize(12);
        return badgeView;
    }

    private void createLeftMenu(LayoutInflater inflater) {
        LinearLayout menuLayout = (LinearLayout) rootView.findViewById(R.id.menu_Layout);
        List<StubObject> leftDrawerMenuStubList = EFAppAccountRegistry.getStubListByElementName
                (EFXmlConstants.ELE_LEFT_DRAWER_MENU);
        if (leftDrawerMenuStubList != null) {
            for (StubObject stub : leftDrawerMenuStubList) {
                View menuItemView = inflater.inflate(R.layout
                        .fragment_app_account_left_drawer_menu_item, menuLayout, false);
                ImageView iconIV = (ImageView) menuItemView.findViewById(R.id.menu_icon);
                iconIV.setImageDrawable(Drawable.createFromPath(EFAppAccountUtils
                        .getAppAccountImagePath() + "/" + stub.getString(EFXmlConstants
                        .ATTR_ICON, "icon")));
                TextView captionTV = (TextView) menuItemView.findViewById(R.id.menu_caption);
                captionTV.setText(stub.getCaption());
                if (stub.getCaption().equals("资源更新")) {
                    //不显示配置文件中的“资源更新”
                    continue;
//                    badgeView = createBadgeView(captionTV);
                }
                menuItemView.setOnClickListener(new MenuOnclickListener(stub.getCaption()));
                menuLayout.addView(menuItemView);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "---------onResume--------");
        if (updateResReceiver == null) {
            // 动态注册广播
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.efounder.updateres");
            updateResReceiver = new UpdateResReceiver();
            getActivity().registerReceiver(updateResReceiver, filter);

            setBadgeView();
        }

    }

    /**
     * 设置资源更新有无角标提醒，资源文件有更新会显示角标
     */
    private void setBadgeView() {
        if (badgeView != null) {
            if (AppAccountResDownloader.isNeedUpdate(EFAppAccountUtils.getAppAccountID())) {
                badgeView.show();
            } else {
                badgeView.hide();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i(TAG, "---------onStop--------");
        if (updateResReceiver != null) {
            getActivity().unregisterReceiver(updateResReceiver);
            updateResReceiver = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "---------onDestroy--------");
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.app_account_exit) {
            //退出应用时，清空缓存数据
            EFAppAccountMainActivity.clearData();
            getActivity().finish();
        }else if (id == R.id.left_drawer_menu_update_resources_layout){
            //资源更新_2 点击提示下载资源
            int appAccountID = getActivity().getIntent().getIntExtra("id", 0);
            new AppAccountResDownloader(getActivity(),appAccountID).updateResource();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.e("==", TAG + "======setUserVisibleHint:isVisibleToUser:" + isVisibleToUser);
        if (isVisibleToUser) {
        }
    }

    public class MenuOnclickListener implements View.OnClickListener {
        private String caption;

        public MenuOnclickListener(String captionTV) {
            this.caption = captionTV;
        }

        @Override
        public void onClick(View view) {
            if (caption.equals("主数据")) {
                Intent intent = new Intent(getActivity(), MasterDataActivity.class);
                getActivity().startActivity(intent);
            }
//            else if (caption.equals("资源更新")) {
//                downResourse();
//            }
        }
    }



    /**
     * 更新资源文件时监听广播，更改角标
     */
    public class UpdateResReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(action)) {
                String num = intent.getStringExtra("num");
                if ("0".equals(num) && badgeView != null) {
                    badgeView.hide();
                }else if("1".equals(num) && badgeView != null){
                    badgeView.show();
                    new AppAccountResDownloader(getActivity(),EFAppAccountUtils.getAppAccountID()).updateResource();
                }
            }
        }
    }
}
